package com.bestcem.xm.member.grpc.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.bp.grpc.v1.base.Page;
import com.bestcem.xm.common.core.domain.web.RpcStatusResult;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.uitls.EnumUtil;
import com.bestcem.xm.member.enums.DeliveryTypeEnum;
import com.bestcem.xm.member.enums.MemberTypeEnum;
import com.bestcem.xm.member.grpc.service.param.PageParam;
import com.bestcem.xm.member.grpc.service.param.member.ListContactMembersParam;
import com.bestcem.xm.member.grpc.service.param.project.FuzzySearchProjectParam;
import com.bestcem.xm.member.grpc.service.param.project.ListFilterProjectManagerParam;
import com.bestcem.xm.member.grpc.v1.common.Member;
import com.bestcem.xm.member.grpc.v1.common.Project;
import com.bestcem.xm.member.grpc.v1.services.*;
import com.bestcem.xm.member.service.MemberService;
import com.bestcem.xm.member.service.ProjectService;
import com.bestcem.xm.member.service.dto.MemberDTO;
import com.bestcem.xm.member.service.dto.PageDTO;
import com.bestcem.xm.member.service.dto.ProjectMemberDto;
import io.grpc.stub.StreamObserver;
import net.devh.boot.grpc.server.service.GrpcService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author dc.wang <dc.wang@idiaoyan.com>
 * @version V1.0
 * @description 投放grpc接口
 * @date 2021/7/27
 */
@GrpcService
public class DeliveryGrpcService extends DeliveryServiceGrpc.DeliveryServiceImplBase {

    private final ProjectService projectService;

    private final MemberService memberService;

    @Autowired
    public DeliveryGrpcService(ProjectService projectService, MemberService memberService){
        this.projectService = projectService;
        this.memberService = memberService;
    }

    @Override
    public void listMembers(ListMembersRequest request, StreamObserver<ListMembersResponse> responseObserver) {
        ListMembersResponse.Builder builder = ListMembersResponse.newBuilder();

        MemberTypeEnum memberTypeEnum = EnumUtil.getEnumByIndex(MemberTypeEnum.class, request.getMemberTypeValue());
        DeliveryTypeEnum deliveryTypeEnum = EnumUtil.getEnumByIndex(DeliveryTypeEnum.class, request.getDeliverTypeValue());
        PageParam pageParam = new PageParam(request.getPage().getPage(), request.getPage().getSize());

        ListContactMembersParam param = new ListContactMembersParam();
        param.setOrgId(request.getOrgId());
        param.setRegex(request.getSearch());
        param.setMemberTypeEnum(memberTypeEnum);
        param.setDeliveryTypeEnum(deliveryTypeEnum);
        param.setPageParam(pageParam);

        // 参数校验

        ServiceResult<PageDTO<MemberDTO>> result = memberService.listMembers(param);
        if(!result.isSuccess()){
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        }else{
            PageDTO<MemberDTO> pageDTO = result.getData();
            builder.setTotal(pageDTO.getTotal());
            builder.addAllMembers(pageDTO.getRows().stream().map(this::convertFrom).collect(Collectors.toList()));
            builder.setStatus(RpcStatusResult.success());
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void fuzzySearchProjectMembers(FuzzySearchProjectRequest request, StreamObserver<FuzzySearchProjectMembersResponse> responseObserver) {
        FuzzySearchProjectMembersResponse.Builder builder = FuzzySearchProjectMembersResponse.newBuilder();

        Page page = request.getPage();
        MemberTypeEnum memberTypeEnum = EnumUtil.getEnumByIndex(MemberTypeEnum.class, request.getMemberTypeValue());

        FuzzySearchProjectParam param = new FuzzySearchProjectParam();
        param.setOrgId(request.getOrgId());
        param.setMemberTypeEnum(memberTypeEnum);
        param.setRegex(request.getRegex());
        param.setPageParam(new PageParam(page.getPage(),page.getSize()));

        ServiceResult<PageDTO<ProjectMemberDto>> result = projectService.fuzzySearchProjectManager(param);
        if(!result.isSuccess()){
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        }else{
            PageDTO<ProjectMemberDto> pageDTO = result.getData();
            builder.setTotal(pageDTO.getTotal());
            builder.addAllProjectMembers(pageDTO.getRows().stream().map(this::convertFrom).collect(Collectors.toList()));
            builder.setStatus(RpcStatusResult.success());
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    private ProjectMember convertFrom(ProjectMemberDto projectMemberDto){
        ProjectMember.Builder projectMemberBuilder = ProjectMember.newBuilder();

        if(projectMemberDto.getMemberDTO() != null){
            MemberDTO memberDTO = projectMemberDto.getMemberDTO();
            Member.Builder memberBuilder = Member.newBuilder();
            memberBuilder.setName(memberDTO.getName());
            memberBuilder.setPhone(memberDTO.getMobile());
            projectMemberBuilder.setMember(memberBuilder);
        }
        Project.Builder projectBuilder = Project.newBuilder();
        projectBuilder.setName(projectMemberDto.getProjectName());
        projectBuilder.setManagerPhone(projectMemberDto.getProjectManagerPhone());
        projectMemberBuilder.setProject(projectBuilder);
        return projectMemberBuilder.build();
    }

    /**
     * 条件查询项目经理信息（project + member）
     * @param request 请求参数
     * @param responseObserver
     * @author dc.wang <dc.wang@idiaoyan.com>
     * @date 2021/6/25
     */
    @Override
    public void filterDeliveryProjects(FilterDeliveryProjectsRequest request, StreamObserver<FilterDeliveryProjectsResponse> responseObserver) {
        FilterDeliveryProjectsResponse.Builder builder = FilterDeliveryProjectsResponse.newBuilder();

        MemberTypeEnum memberTypeEnum = EnumUtil.getEnumByIndex(MemberTypeEnum.class, request.getMemberTypeValue());

        ListFilterProjectManagerParam param = new ListFilterProjectManagerParam();
        param.setOrgId(request.getOrgId());
        param.setMemberTypeEnum(memberTypeEnum);
        param.setUserId(request.getUserId());
        param.setSuperRole(request.getSuperAdmin() ? 1 : 0);
        param.setIsSenior(request.getSeniorAdmin() ? 1 : 0);
        try {
            JSONObject jsonCondition = JSON.parseObject(request.getCondition());
            param.setCondition(jsonCondition.getString("condition"));
        }catch (Exception e){
            builder.setStatus(RpcStatusResult.error("condition 参数异常"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        ServiceResult<PageDTO<ProjectMemberDto>> result = projectService.listFilterProjectManager(param);
        if(!result.isSuccess()){
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        }else{
            List<Project> projectList = result.getData().getRows().stream().map(this::convert).collect(Collectors.toList());
            builder.addAllProjects(projectList);
            builder.setStatus(RpcStatusResult.success());
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    // fixme 参数返回待补充
    private Project convert(ProjectMemberDto dto){
        Project.Builder builder = Project.newBuilder();
        builder.setId(dto.getProjectId());
        builder.setName(dto.getProjectName());
        builder.setCode(dto.getProjectCode());
        builder.setStatus(dto.getProjectName());
        return builder.build();
    }

    private Member convertFrom(MemberDTO memberDTO){
        Member.Builder builder = Member.newBuilder();
        builder.setName(memberDTO.getName());
        builder.setPhone(memberDTO.getMobile());
        builder.setInstituteName(memberDTO.getInstituteName());
        builder.setId(memberDTO.getId());
        return builder.build();
    }
}
